// 使用 require 引入
const aliSdk = require("../../utils/aliIot-sdk.js");
const app = getApp();
let debounceTimer = null // 定义防抖定时器

Page({

  /**
   * 页面的初始数据
   */
  data: {
    levels: ['1档', '2档', '3档'], // 档位选项
    currentLevel: '- -', // 初始档位为0
    product_type: '', //产品类型
    deviceName: '',
    // 只读取的参数
    local_dev_status: "- -",//手机端设备运行状态
    // 盐疗参数
    salt_concentration: 0,//盐浓度
    salt_timing: 0,//盐疗定时
    temperature: 0,//温度档位
    salt_add_time: 0,//盐疗定时初始值
    //氧疗参数
    oxygen_flow: 0,//氧流量
    oxygen_dtime: 0,// 制氧定时界面显示
    oxygen_dtime_show: 0,// 制氧定时最大值
    oxygen_time: "- -",//制氧运行时间
    total_time: "- -",//盐疗累计运行时间
    oxygen_concentration: "0",//氧浓度
    oxtotal_time: 0,//制氧累计时间

    //公共参数
    err_code: 0,
    powerSwitch: 0,//控制开关
    dev_status: "- -",//云端设备运行状态
    work_mode: 0,//工作模式
    screen_off: 0,//亮度档位
    dark_mode: 0,//夜间模式
    //开关按钮
    states: ['关机', '开机', '启动'],
    currentIndex: 0,
    buttonText: '关机',

    //开关状态
    states_png: ['end.png', 'start.png', 'run.png'],
    currentIndex_png: 0,
    buttonText_png: 'end.png',
    show_index: false,

    //定时器---
    timer: null,
    //定时器---
    // 产品类型
    mode_type: 0,
    //不同型号设备最大参数
    salt_concentration_max: 0, //盐浓度最大
    salt_timing_max: 0,//盐疗定时最大时长
    selected: null, //模式选中按钮颜色

  },

  /**
   * 默认首页产品图
   */
  previewImage: function () {
    wx.previewImage({
      current: '../img/salt.png', // 当前显示图片的链接
      urls: ['https://gitee.com/tpyszc/tpyszc_image/raw/master/salt.png', 'https://gitee.com/tpyszc/tpyszc_image/raw/master/xns.png'] // 需要预览的图片链接列表
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function () {
    const that = this;
    that.get_devname_product_type();
    if (that.data.product_type === 'a1L4GogBzON') {
      wx.redirectTo({
        url: '/pages/mof/mof'
      });
    } else if (that.data.product_type === 'a11uQJCzUPe') {
      that.setData({
        show_index: true
      })
    } else {
      wx.redirectTo({
        url: '/pages/index/index'
      });
    }
  },

  /**
   * 缓存中获取设备编号+产品类型
   */
  get_devname_product_type: function () {
    const that = this;
    const deviceName = wx.getStorageSync('deviceName'); // 从本地获取值
    const product_type = wx.getStorageSync('product_type');
    const mode_type = wx.getStorageSync('mode_type');
    if (mode_type == 90 || mode_type == 95) {
      that.setData({
        deviceName: deviceName,
        product_type: product_type,
        mode_type: mode_type,
        salt_concentration_max: 10, //盐浓度最大
        salt_timing_max: 90,//盐疗定时最大时长
        oxygen_dtime_show: 120//氧疗定时最大时长
      })
    }
    if (mode_type == 91 || mode_type == 96) {
      that.setData({
        deviceName: deviceName,
        product_type: product_type,
        mode_type: mode_type,
        salt_concentration_max: 15, //盐浓度最大
        salt_timing_max: 60,//盐疗定时最大时长
        oxygen_dtime_show: 120//氧疗定时最大时长
      })
    }
    if (mode_type == 94 || mode_type == 99) {
      that.setData({
        deviceName: deviceName,
        product_type: product_type,
        mode_type: mode_type,
        salt_concentration_max: 30, //盐浓度最大
        salt_timing_max: 90,//盐疗定时最大时长
        oxygen_dtime_show: 480//氧疗定时最大时长
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染（获取设备编码+产品名称）
   */
  onReady() {
    const that = this;
    that.get_devname_product_type();
    if (that.data.product_type === 'a1L4GogBzON') {
      wx.redirectTo({
        url: '/pages/mof/mof'
      });
    } else if (that.data.product_type === 'a11uQJCzUPe') {
      that.setData({
        show_index: true
      })
    } else {
      wx.redirectTo({
        url: '/pages/index/index'
      });
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    const that = this;
    that.get_devname_product_type();
    if (that.data.product_type === 'a1L4GogBzON') {
      wx.redirectTo({
        url: '/pages/mof/mof'
      });
    } else if (that.data.product_type === 'a11uQJCzUPe') {
      that.setData({
        show_index: true
      })
    } else {
      wx.redirectTo({
        url: '/pages/index/index'
      });
    }

    if (that.data.currentIndex != 0) {
      that.startAliyun();
    } else {
      that.aliyun_default();
      that.stopAliyun();
      that.stopApiCall();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    this.stopApiCall();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    this.stopApiCall();
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
  },

  /**
   * 弹框--打开设备提示
   * @param {*} e 
   */
  open_dev: function () {
    this.stopApiCall();
    wx.showToast({
      title: '请打开设备',
      duration: 1400,
      mask: true,
      image: '../img/end.png'
    });
  },

  /**
   * 自定义方法--数据转换
   * @param {*} 步进值 ±1/0.1 
   * @param {*} 字符转数字 
   * @param {*} 小数/整数 
   */
  button_int_number: function (number1, number2, number3) {
    if (number3 == 1) {
      const formatting_number = parseInt(number1) + parseInt(number2);
      return formatting_number;
    } else if (number3 == 2) {
      const formatting_number2 = parseFloat(number2);
      return number1 + formatting_number2;
    } else if (number3 == 3) {
      const result = parseInt(number1) - parseInt(number2);
      return result;
    } else {
      wx.showToast({
        title: '设备连接异常',
        icon: 'err',
        duration: 1500,
      });
    }
  },

  /**
   *弹框 -- 发送数据到云端成功
   * @param {*} e 
   */
  send_aliyun_iot() {
    wx.showToast({
      title: '发送成功',
      duration: 2000,
      mask: true,
      image: '../img/send_aliyun.png'
    });
  },

  /**
   * * 定时器开始--2秒一次调用云平台数据
   */
  flush_data: function () {
    // 请求成功  res回response数据
    const that = this;
    if (that.data.currentIndex != 0) {
      that.interval = setInterval(() => {
        that.loadData();
      }, 2000);
    } else {
      that.stopApiCall();
    }
  },

  /**
 * * 定时器开始--2秒一次调用云平台数据
 */
  startAliyun: function () {
    if (this.data.timer) {
      return
    }
    this.data.timer = setInterval(() => {
      this.loadData();
    }, 1500)
  },

  /**
 * * 定时器结束
 */
  stopAliyun: function () {
    if (this.data.timer) {
      clearInterval(this.data.timer)
      this.data.timer = null
    }
  },

  /**
   * 定时器停止
   */
  stopApiCall: function () {
    const that = this;
    // 清除定时器
    if (that.interval) {
      clearInterval(that.interval);
    }
  },

  /**
   * 获取云端数据
   */
  loadData: function () {
    const that = this;
    aliSdk.request({
      Action: "QueryDevicePropertyStatus",
      ProductKey: that.data.product_type,
      DeviceName: that.data.deviceName
    }, {
      method: "POST"
    },
      (res) => {
        if (res.data.Success) {
          that.usd_setPropertyData(res.data.Data.List.PropertyStatusInfo);
        } else {
          wx.showToast({
            title: '设备连接失败',
            icon: 'error',
            duration: 1500,
          });
          that.stopApiCall();
        }
      },
      (res) => {
        // 默认都会执行
        // that.setPropertyData(res.data.Data.List.PropertyStatusInfo);
      }
    )
  },


  /**
 * 台式--获取阿里云端数据并更新页面数据
 */
  usd_setPropertyData: function (infos) {
    const that = this;
    // 西纳舒岩盐气溶胶治疗仪
    var propertys = that.convertPropertyStatusInfo(infos);
    that.setData({
      // 只读取的参数
      total_time: propertys.total_time,//累计运行时间
      dev_status: propertys.dev_status,//设备运行状态
      err_code: propertys.err_code,//异常状态码
      // 手动设置参数
      salt_concentration: propertys.salt_concentration,//盐浓度
      salt_timing: propertys.salt_timing,//盐疗定时
      salt_add_time: propertys.salt_add_time,//盐疗定时初始值
      temperature: propertys.temperature,//温度档位
      powerSwitch: propertys.powerSwitch,//控制开关
      screen_off: propertys.screen_off, //亮度模式
      dark_mode: propertys.dark_mode //夜间模式
    });

    // 夜间模式
    if (that.data.dark_mode == 1) {
      wx.showToast({
        title: '夜间模式已打开',
        image: '../img/night.png',
        duration: 2500,
        mask: true
      })
    }

    // 开关机按钮
    if (that.data.powerSwitch == 1) {
      that.setData({
        currentIndex: 1,
        buttonText: that.data.states[1],
        currentIndex_png: 1,
        buttonText_png: that.data.states_png[1],

        local_dev_status: "待机",//手机端设备运行状态
      })
    } else if (that.data.powerSwitch == 2) {
      // 盐疗
      that.setData({
        currentIndex: 2,
        buttonText: that.data.states[2],
        currentIndex_png: 2,
        buttonText_png: that.data.states_png[2],
        local_dev_status: "运行",//手机端设备运行状态
      })
    } else {
      // 停止治疗
      that.setData({
        currentIndex: 0,
        buttonText: that.data.states[0],
        currentIndex_png: 0,
        buttonText_png: that.data.states_png[0],
        total_time: "- -",//累计运行时间
        local_dev_status: "- -",//手机端设备运行状态
        dev_status: "- -",//云端设备运行状态
        salt_concentration: "- -",//盐浓度
        salt_timing: "- -",//盐疗定时
        err_code: "",//异常状态码
        currentLevel: '- -', // 更新当前档位
        temperature: "- -"//温度档位
      });
      that.stopApiCall();
    }

    //亮度档位
    if (that.data.screen_off == 0) {
      that.setData({
        currentLevel: that.data.levels[0] // 更新当前档位
      })
    } else {
      that.setData({
        currentLevel: that.data.levels[that.data.screen_off] // 更新当前档位
      })
    }

    // 如果出现报警，设备变成待机模式
    if (that.data.err_code == 0) {
      that.setData({
        err_code: that.data.err_code // 更新当前档位
      })
    } else {
      that.setData({
        currentIndex: 1,
        buttonText: that.data.states[1],
        currentIndex_png: 1,
        buttonText_png: that.data.states_png[1],
      })
    }

    // 盐疗时长结束，停止刷新数据，设备变成待机模式
    if (that.data.salt_timing == 0) {
      that.setData({
        currentIndex: 1,
        buttonText: that.data.states[1],
        currentIndex_png: 1,
        buttonText_png: that.data.states_png[1],
        local_dev_status: "待机",//手机端设备运行状态
      })
      that.stopApiCall();
    }

  },

  /**
   * 默认参数
   */
  aliyun_default: function () {
    const that = this;
    // 停止治疗
    that.setData({
      currentIndex: 0,
      buttonText: that.data.states[0],
      currentIndex_png: 0,
      buttonText_png: that.data.states_png[0],
      total_time: "- -",//累计运行时间
      local_dev_status: "- -",//手机端设备运行状态
      dev_status: "- -",//云端设备运行状态
      salt_concentration: "- -",//盐浓度
      salt_timing: "- -",//盐疗定时
      err_code: "",//异常状态码
      currentLevel: '- -', // 更新当前档位
      temperature: "- -"//温度档位
    });
  },

  /**
   * 浓度调节
   * @param {*} e 
   */
  salt_concentration_minus: function (e) {
    const that = this;
    that.stopAliyun();
    const salt_concentration_number = that.button_int_number(e.currentTarget.dataset.operation, that.data.salt_concentration, 1);
    if (that.data.powerSwitch == 1 || that.data.powerSwitch == 2) {

      // 获取最大可调物化时间
      if (salt_concentration_number >= 5 && salt_concentration_number <= that.data.salt_concentration_max) {
        that.setData({
          salt_concentration: salt_concentration_number
        });
        // 防抖处理：清除之前的定时器
        if (debounceTimer) {
          clearTimeout(debounceTimer);
        }
        // 设置新的定时器，3秒后更新最终值饿了
        debounceTimer = setTimeout(() => {
          aliSdk.request({
            Action: "SetDeviceProperty",
            ProductKey: that.data.product_type,
            DeviceName: that.data.deviceName,
            Items: "{salt_concentration:" + salt_concentration_number + "}",
            Args: "" //无参服务，所以传空
          }, {
            method: "POST"
          },
            (res) => {
              this.onShow();
            })
        }, 800); // 延迟1秒执行

      } else {
        this.onShow();
        wx.showModal({
          title: '提示',
          content: '调节范围在5到' + that.data.salt_concentration_max + '之间。',
          showCancel: false, // 不显示取消按钮
        });
      }

    } else {
      this.open_dev();
    }

  },

  /**
  * 盐疗-定时按钮 加 减
  */
  salt_timing_minus: function (e) {
    const that = this;
    that.stopAliyun();
    // 盐疗定时最大定时时长
    const powerSwitch = parseInt(that.data.powerSwitch);
    const salt_max = parseInt(that.data.salt_timing_max);
    // 页面显示盐疗定时
    // 界面值 +-5
    const salt_timing_result = that.button_int_number(e.currentTarget.dataset.operation, that.data.salt_timing, 1);
    // 盐疗定时初始值 +-5
    const salt_default_result = that.button_int_number(e.currentTarget.dataset.operation, that.data.salt_add_time, 1);
    that.setData({
      salt_add_time: salt_default_result
    });
    const salt_add_time = parseInt(that.data.salt_add_time);
    //判断定时时间  10<=盐疗定时（界面显示调节参数）<=最大定时时长

    if (powerSwitch == 0) {
      this.open_dev();
    }
    if (powerSwitch == 1) {
      if (10 <= salt_timing_result && salt_timing_result <= salt_max) {
        // 设备待机或者运行
        that.setData({
          salt_timing: salt_timing_result
        });

        // 防抖处理：清除之前的定时器
        if (debounceTimer) {
          clearTimeout(debounceTimer);
        }
        // 设置新的定时器，3秒后更新最终值饿了
        debounceTimer = setTimeout(() => {
          aliSdk.request({
            Action: "SetDeviceProperty",
            ProductKey: that.data.product_type,
            DeviceName: that.data.deviceName,
            Items: "{salt_timing:" + salt_timing_result + "}",
            Args: "" //无参服务，所以传空
          }, {
            method: "POST"
          },
            (res) => {
              this.onShow();
            })
        }, 800); // 延迟1秒执行

      } else {
        this.onShow();
        //判断定时时间  10<=盐疗定时（界面显示调节参数）<=最大定时时长
        wx.showModal({
          title: '提示',
          content: '调节范围在10到' + salt_max + '之间。',
          showCancel: false, // 不显示取消按钮
        });
      }

    }
    if (powerSwitch == 2) {
      // 盐疗定时初始值是<=最大时长
      //判断定时时间  10<=盐疗定时（界面显示调节参数）<=最大定时时长
      if (10 <= salt_timing_result && salt_timing_result <= salt_max) {
        if (salt_add_time >= 10 && salt_add_time <= salt_max) {
          // 设备待机或者运行
          that.setData({
            salt_timing: salt_timing_result
          });
          // 防抖处理：清除之前的定时器
          if (debounceTimer) {
            clearTimeout(debounceTimer);
          }
          // 设置新的定时器，3秒后更新最终值饿了
          debounceTimer = setTimeout(() => {
            aliSdk.request({
              Action: "SetDeviceProperty",
              ProductKey: that.data.product_type,
              DeviceName: that.data.deviceName,
              Items: "{salt_timing:" + salt_timing_result + "}",
              Args: "" //无参服务，所以传空
            }, {
              method: "POST"
            },
              (res) => {
                this.onShow();
              })
          }, 800); // 延迟1秒执行

        } else {
          this.onShow();
          wx.showModal({
            title: '提示',
            content: '调节范围在10到' + salt_max + '之间。',
            showCancel: false, // 不显示取消按钮
          });
        }
      } else {
        this.onShow();
        wx.showModal({
          title: '提示',
          content: '调节范围在10到' + salt_max + '之间。',
          showCancel: false, // 不显示取消按钮
        });
      }
    }

  },

  /**
  * 公用--开关机按钮
  */
  changeState: function () {
    const that = this;
    let nextIndex = (that.data.currentIndex + 1) % that.data.states.length;
    // 判断设备异常状态，若为异常，开关按钮设为1处于待机模式
    if (that.data.err_code == 0) {
      that.setData({
        currentIndex: nextIndex,
        buttonText: that.data.states[nextIndex],
        currentIndex_png: nextIndex,
        buttonText_png: that.data.states_png[nextIndex],
        selected: null
      });
      aliSdk.request({
        Action: "SetDeviceProperty",
        ProductKey: that.data.product_type,
        DeviceName: that.data.deviceName,
        Items: "{powerSwitch:" + nextIndex + "}",
        Args: "" //无参服务，所以传空
      }, {
        method: "POST"
      },
        (res) => {

          if (that.data.currentIndex == 1) {
            wx.showToast({
              title: '连接中...',
              duration: 4000,
              mask: true,
              image: '../img/send_aliyun.png'
            });
          }
          that.onShow();
          if (that.data.currentIndex == 2 || that.data.currentIndex == 0) {
            wx.showToast({
              title: '传输中...',
              duration: 4000,
              mask: true,
              image: '../img/send_aliyun.png'
            });
          }


        })

    } else {
      // wx.showToast({
      //   title: '异常,请检查',
      //   icon: 'error',
      //   duration: 2000,
      //   mask: true
      // })
      aliSdk.request({
        Action: "SetDeviceProperty",
        ProductKey: that.data.product_type,
        DeviceName: that.data.deviceName,
        Items: "{powerSwitch:" + nextIndex + "}",
        Args: "" //无参服务，所以传空
      }, {
        method: "POST"
      },
        (res) => {

          if (that.data.currentIndex == 1) {
            wx.showToast({
              title: '连接中...',
              duration: 4000,
              mask: true,
              image: '../img/send_aliyun.png'
            });
          }
          that.onShow();
          if (that.data.currentIndex == 2 || that.data.currentIndex == 0) {
            wx.showToast({
              title: '传输中...',
              duration: 4000,
              mask: true,
              image: '../img/send_aliyun.png'
            });
          }
        })
    }
  },


  /**
  * 公用--温度调节按钮 加 减
  */
  temperature_minus: function (e) {
    const that = this;
    that.stopAliyun();
    const temperature_result = that.button_int_number(e.currentTarget.dataset.operation, that.data.temperature, 1);
    if (that.data.currentIndex == 1 || that.data.currentIndex == 2) {
      if (temperature_result >= 1 && temperature_result <= 3) {
        that.setData({
          temperature: temperature_result
        });
        // 防抖处理：清除之前的定时器
        if (debounceTimer) {
          clearTimeout(debounceTimer);
        }
        // 设置新的定时器，3秒后更新最终值
        debounceTimer = setTimeout(() => {
          aliSdk.request({
            Action: "SetDeviceProperty",
            ProductKey: that.data.product_type,
            DeviceName: that.data.deviceName,
            Items: "{temperature:" + temperature_result + "}",
            Args: "" //无参服务，所以传空
          }, {
            method: "POST"
          },
            (res) => {
              this.onShow();
            })
        }, 800); // 延迟1秒执行
      } else {
        this.onShow();
        wx.showModal({
          title: '提示',
          content: '调节范围在1到3之间。',
          showCancel: false, // 不显示取消按钮
        });

      }
    } else {
      that.open_dev();
    }

  },

  /**
  * 公用--亮度档位调节
  * @param {*} e 
  */
  onLevelChange: function (e) {
    const that = this;
    that.stopAliyun();
    if (that.data.currentIndex == 1 || that.data.currentIndex == 2) {
      that.setData({
        currentLevel: that.data.levels[e.detail.value] // 更新当前档位
      });

      // 防抖处理：清除之前的定时器
      if (debounceTimer) {
        clearTimeout(debounceTimer);
      }
      // 设置新的定时器，3秒后更新最终值
      debounceTimer = setTimeout(() => {
        aliSdk.request({
          Action: "SetDeviceProperty",
          ProductKey: that.data.product_type,
          DeviceName: that.data.deviceName,
          Items: "{screen_off:" + e.detail.value + "}",
          Args: "" //无参服务，所以传空
        }, {
          method: "POST"
        },
          (res) => {
            this.onShow();
          })
      }, 800); // 延迟1秒执行

    } else {
      this.open_dev();
    }
  },

  /**
   * 将返回结果转成key,value的json格式方便使用
   * @param {*} infos
   */
  convertPropertyStatusInfo: function (infos) {
    var data = {}
    infos.forEach((item) => {
      data[item.Identifier] = item.Value ? item.Value : null
    })
    return data
  },

  /**
   * 请绑定设备按钮
   */
  jump: function () {
    wx.switchTab({
      url: '/pages/user/user' // 跳转到主页
    });
  }

})